package com.generalbackend.controller;

import com.generalbackend.common.annotion.ApiPermission;
import com.generalbackend.common.model.CommonResult;
import com.generalbackend.common.service.IFileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 公共文件上传下载类
 * @author tim.xie
 * @date 2022/7/8 17:30
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/common/file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @ApiOperation(httpMethod = "POST", value = "公共文件上传")
    @ApiPermission(name = "公共文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public CommonResult upload(@RequestParam("file") MultipartFile file) {
        String path = null;
        try {
            path = fileService.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.errorCommonResult("公共文件上传失败");
        }
        String url = "/api/common/file/download/" + path;
        return CommonResult.successCommonResult(url, "公共文件上传成功");
    }

    @ApiOperation(httpMethod = "GET", value = "公共文件下载")
    @ApiPermission(name = "公共文件下载")
    @RequestMapping(value = "/download/{childDir}/{randomFolder}/{filename}", method = RequestMethod.GET)
    public void uploadFile(HttpServletResponse response,
                                   @PathVariable("childDir") String childDir,
                                   @PathVariable("randomFolder") String randomFolder,
                                   @PathVariable("filename") String filename) {
        fileService.downloadFile(response, childDir, randomFolder, filename);
    }

}
